<template>
  <basic-container>
    <avue-crud
      ref="crud"
      v-model="form"
      :option="option"
      :table-loading="loading"
      :data="data"
      :page="page"
      :before-open="beforeOpen"
      :cell-style="cellStyle"
      :row-style="rowStyle"
      @row-click="rowClick"
      @refresh-change="refresh"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button
          type="primary"
          size="medium"
          icon="el-icon-menu"
          @click="handleCustomMenu"
        >
          自定义菜单
        </el-button>
        <el-button
          type="primary"
          size="medium"
          icon="el-icon-user"
          @click="handleUserList"
        >
          关注粉丝列表
        </el-button>
        <el-button
          type="primary"
          size="medium"
          icon="el-icon-notebook-2"
          @click="handleArticlePublish"
        >
          文章发布
        </el-button>
      </template>
      <template
        slot="menu"
        slot-scope="{row}"
      >
        <el-button type="text" icon="el-icon-menu" size="medium" @click.stop="handleMenu(row)">
          自定义菜单
        </el-button>
      </template>
    </avue-crud>
    <!--    自定义菜单-->
    <el-dialog
      :visible.sync="menuShow"
      :fullscreen="false"
      title="公众号菜单设置"
      modal-append-to-body
      append-to-body
      width="70%"
      @close="handleMenuHide"
    >
      <div>
        <div id="app-menu">
          <!-- 预览窗 -->
          <div class="weixin-preview">
            <div class="weixin-bd">
              <ul id="weixin-menu" class="weixin-menu">
                <li
                  v-for="(btn,i) in mpMenu.buttons"
                  :key="i"
                  :class="{current:selectedMenuIndex===i&&selectedMenuLevel==1}"
                  class="menu-item"
                  @click="selectMenu(i)"
                >
                  <div class="menu-item-title">
                    <span>{{ btn.name }}</span>
                  </div>
                  <ul v-show="selectedMenuIndex===i" class="weixin-sub-menu">
                    <li
                      v-for="(sub,i2) in btn.subButtons"
                      :key="i2"
                      :class="{current:selectedSubMenuIndex===i2&&selectedMenuLevel==2}"
                      class="menu-sub-item"
                      @click.stop="selectSubMenu(i2)"
                    >
                      <div class="menu-item-title">
                        <span>{{ sub.name }}</span>
                      </div>
                    </li>
                    <li v-if="btn.subButtons.length<5" class="menu-sub-item" @click.stop="addMenu(2)">
                      <div class="menu-item-title">
                        <i class="el-icon-plus" />
                      </div>
                    </li>
                    <i class="menu-arrow arrow_out" />
                    <i class="menu-arrow arrow_in" />
                  </ul>
                </li>
                <li v-if="mpMenu.buttons.length<3" class="menu-item" @click="addMenu(1)">
                  <i class="el-icon-plus" />
                </li>
              </ul>
            </div>
          </div>
          <!-- 菜单编辑器 -->
          <div v-if="selectedMenuLevel>0" class="weixin-menu-detail">
            <wx-menu-button-editor :button="selectedButton" :selected-menu-level="selectedMenuLevel" @delMenu="delMenu" />
          </div>
        </div>
        <div class="weixin-btn-group" @click="updateWxMenu">
          <el-button type="success" icon="el-icon-upload">
            发布
          </el-button>
          <el-button type="warning" icon="el-icon-delete" @click="delMenu">
            清空
          </el-button>
        </div>
      </div>
    </el-dialog>
    <!--    用户列表-->
    <el-dialog
      :visible.sync="userShow"
      title="公众号关注粉丝列表"
      modal-append-to-body
      append-to-body
      fullscreen
      @close="handleUserHide"
    >
      <avue-crud
        ref="userCrud"
        v-model="userForm"
        :option="userOption"
        :table-loading="userLoading"
        :data="userData"
        :page="userPage"
        @refresh-change="refreshUser"
        @current-change="currentUserChange"
        @size-change="sizeUserChange"
        @on-load="onUserLoad"
      >
        <template slot="menuLeft">
          <div class="tip">
            <p>注意：最多一次只能拉取1000个微信公众号粉丝数！</p>
          </div>
        </template>
        <!--        <template slot="headImgUrl" slot-scope="{row}">-->
        <!--          <img :src="row.headImgUrl" height="50" width="50">-->
        <!--        </template>-->
      </avue-crud>
    </el-dialog>
  </basic-container>
</template>

<script>
import { mapGetters } from 'vuex'
import { formatDateTime } from '@/util/DateUtil'

const getWxMpPageListAction = 'lib/wx/getWxMpPageList'
const updateWxMpMenuAction = 'lib/wx/updateWxMpMenu'
const listWxMpMenuAction = 'lib/wx/listWxMpMenu'
const getWxMpUserPageListAction = 'lib/wx/listWxMpUser'
export default {
  name: 'WX',
  components: {
    wxMenuButtonEditor: () => import('./-menu')
  },
  data () {
    return {
      userOption: {
        pageSize: 100,
        border: true,
        menu: false,
        lazy: true,
        tip: true,
        header: true,
        tipPlacement: 'top-start',
        index: true,
        indexLabel: '序号',
        indexFixed: true,
        selection: true,
        selectionWidth: 60,
        selectionFixed: false,
        searchBtn: false,
        searchShow: false,
        searchMenuSpan: 4,
        refreshBtn: true,
        addBtn: false,
        viewBtn: true,
        editBtn: false,
        delBtn: false,
        excelBtn: true,
        printBtn: false,
        dialogDrag: true,
        dialogDirection: 'rtl',
        dialogType: 'dialog',
        column: [
          {
            label: '头像',
            prop: 'headImgUrl',
            dataType: 'string',
            type: 'img',
            slot: true,
            width: 80
          },
          {
            label: '昵称',
            prop: 'nickname',
            type: 'input',
            search: true,
            width: 130
          },
          {
            label: 'openid',
            prop: 'openId',
            type: 'input',
            width: 260
          },
          {
            label: '性别',
            prop: 'sexDesc',
            type: 'input',
            width: 70
          },
          {
            label: '城市',
            prop: 'city',
            type: 'input',
            formatter: this.formatUserCity
          },
          {
            label: '订阅时间',
            prop: 'subscribeTime',
            type: 'input',
            formatter: this.formatUserDateTime
          }
        ]
      },
      userForm: {},
      userQuery: { nextOpenid: null },
      userLoading: true,
      userPage: {
        pageSize: 100,
        currentPage: 1,
        total: 0
      },
      userData: [],
      userShow: false,
      mpMenu: { buttons: [] }, // 当前菜单
      selectedMenuIndex: '', // 当前选中菜单索引
      selectedSubMenuIndex: '', // 当前选中子菜单索引
      selectedMenuLevel: 0, // 选中菜单级别
      selectedButton: '', // 选中的菜单按钮
      appId: null,
      menuShow: false,
      // 公众号列表
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        // title: '参数配置表',
        border: true,
        menu: true,
        lazy: true,
        tip: true,
        tipPlacement: 'top-start',
        index: true,
        indexLabel: '序号',
        indexFixed: true,
        selection: true,
        selectionWidth: 60,
        selectionFixed: false,
        addBtn: false,
        viewBtn: true,
        editBtn: false,
        delBtn: false,
        excelBtn: false,
        printBtn: false,
        dialogDrag: true,
        dialogDirection: 'rtl',
        dialogType: 'dialog',
        column: [
          {
            label: '公众号名称',
            prop: 'name',
            type: 'input',
            span: 24,
            showWordLimit: true,
            maxlength: 200,
            width: 130,
            labelWidth: 130,
            hide: false,
            showColumn: true,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: true,
              message: '请输入公众号名称',
              trigger: 'blur'
            }]
          },
          {
            label: 'appId',
            prop: 'appId',
            showWordLimit: true,
            maxlength: 200,
            labelWidth: 130,
            span: 24,
            type: 'input',
            hide: false,
            showColumn: true,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: true,
              message: '请输入公众号对应的appId',
              trigger: 'blur'
            }]
          },
          {
            label: 'secret',
            prop: 'secret',
            type: 'input',
            hide: false,
            showWordLimit: true,
            maxlength: 200,
            labelWidth: 130,
            span: 24,
            showColumn: true,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true,
            rules: [{
              required: true,
              message: '请输入公众号对应的secret',
              trigger: 'blur'
            }]
          },
          {
            label: 'token',
            prop: 'token',
            type: 'input',
            span: 24,
            labelWidth: 130,
            showColumn: true,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true
          },
          {
            label: 'aesKey',
            prop: 'aesKey',
            type: 'input',
            showWordLimit: true,
            maxlength: 500,
            span: 24,
            labelWidth: 130,
            hide: true,
            showColumn: false,
            overHidden: true,
            addDisplay: true,
            editDisplay: true,
            viewDisplay: true
          }
        ]
      },
      data: []
    }
  },
  computed: {
    ...mapGetters(['permissions', 'website']),
    ids () {
      const ids = []
      this.selectionList.forEach((e) => {
        ids.push(e.appId)
      })
      return ids
    }
  },
  methods: {
    formatUserCity (row, value, label, column) {
      return row.country + ', ' + row.province + ', ' + row.city
    },
    formatUserDateTime (row, value, label, column) {
      return formatDateTime(row.subscribeTime * 1000)
    },
    handleArticlePublish () {
      if (this.selectionList.length !== 1) {
        this.$message.warning('请选择一个公众号')
      }
    },
    handleUserList () {
      if (this.selectionList.length !== 1) {
        this.$message.warning('请选择一个公众号')
        return
      }
      this.appId = this.ids[0]
      this.userShow = true
      this.userQuery.nextOpenid = null
      this.onUserLoad(this.userPage)
    },
    handleUserHide () {
      this.userShow = false
    },
    refreshUser ({ page, searchForm }) {
      this.userQuery.nextOpenid = null
      this.onUserLoad(page)
    },
    currentUserChange (currentPage) {
      this.userPage.currentPage = currentPage
    },
    sizeUserChange (pageSize) {
      this.userPage.pageSize = pageSize
    },
    onUserLoad (page, params = {}) {
      this.userLoading = true
      let queryData = {
        pageNo: page.currentPage,
        pageSize: page.pageSize
      }
      queryData = Object.assign(queryData, Object.assign(params, this.userQuery))
      this.$store.dispatch(getWxMpUserPageListAction, { appId: this.appId, query: queryData }).then((res) => {
        this.userLoading = false
        const resCode = res.code
        const errorMsg = res.message
        if (resCode === 0) {
          const data = res.data
          this.userPage.total = parseInt(data.total)
          this.userData = data.records
          this.userQuery.nextOpenid = data.nextOpenid
          this.selectionClear()
        } else {
          this.$message({
            type: 'error',
            showClose: true,
            message: errorMsg || '查询数据失败,请稍后再试!'
          })
        }
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'error',
          showClose: true,
          message: '查询数据异常,请稍后再试!'
        })
      })
    },
    getWxMenu () {
      this.$store.dispatch(listWxMpMenuAction, { appId: this.appId })
        .then((res) => {
          if (res.code === 0) {
            this.mpMenu = res.data.menu || { buttons: [] }
          } else {
            const message = res.message
            this.$message({
              type: 'error',
              showClose: true,
              message
            })
          }
        }).catch((err) => {
          console.log(err)
          this.$message({
            type: 'error',
            showClose: true,
            message: '查询数据异常,请稍后再试!'
          })
        })
    },
    // 选中主菜单
    selectMenu (i) {
      this.selectedMenuLevel = 1
      this.selectedSubMenuIndex = ''
      this.selectedMenuIndex = i
      this.selectedButton = this.mpMenu.buttons[i]
    },
    // 选中子菜单
    selectSubMenu (i) {
      this.selectedMenuLevel = 2
      this.selectedSubMenuIndex = i
      this.selectedButton = this.mpMenu.buttons[this.selectedMenuIndex].subButtons[i]
    },
    // 添加菜单
    addMenu (level) {
      if (level === 1 && this.mpMenu.buttons.length < 3) {
        this.mpMenu.buttons.push({
          type: 'view',
          name: '菜单名称',
          subButtons: [],
          url: ''
        })
        this.selectMenu(this.mpMenu.buttons.length - 1)
      }
      if (level === 2 && this.mpMenu.buttons[this.selectedMenuIndex].subButtons.length < 5) {
        this.mpMenu.buttons[this.selectedMenuIndex].subButtons.push({
          type: 'view',
          name: '子菜单名称',
          url: ''
        })
        this.selectSubMenu(this.mpMenu.buttons[this.selectedMenuIndex].subButtons.length - 1)
      }
    },
    // 删除菜单
    delMenu () {
      if (this.selectedMenuLevel === 1 && confirm('删除后菜单下设置的内容将被删除')) {
        this.mpMenu.buttons.splice(this.selectedMenuIndex, 1)

        this.selectedMenuLevel = 0// 删除主菜单后不选中任何菜单
        this.selectedMenuIndex = ''
        this.selectedSubMenuIndex = ''
        this.selectedButton = ''
      } else if (this.selectedMenuLevel === 2) {
        this.mpMenu.buttons[this.selectedMenuIndex].subButtons.splice(this.selectedSubMenuIndex, 1)

        this.selectedMenuLevel = 1// 删除后选中主菜单不选子菜单
        this.selectedSubMenuIndex = ''
        this.selectedButton = this.mpMenu.buttons[this.selectedMenuIndex]
      }
    },
    updateWxMenu () {
      this.$store.dispatch(updateWxMpMenuAction, { appId: this.appId, menu: this.mpMenu })
        .then((res) => {
          if (res.code === 0) {
            this.menuShow = false
            this.$message({
              message: '操作成功',
              type: 'success'
            })
          } else {
            const message = res.message
            this.$message({
              type: 'error',
              showClose: true,
              message
            })
          }
        }).catch((err) => {
          this.$message({
            type: 'error',
            showClose: true,
            message: err
          })
        })
    },
    handleMenuHide () {
      this.menuShow = false
    },
    handleMenu (row) {
      this.menuShow = true
      this.mpMenu = { buttons: [] }
      this.appId = row.appId
      this.getWxMenu()
    },
    rowStyle ({ row, column, rowIndex }) {
      return {}
    },
    cellStyle ({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 2) {
        return {
          fontWeight: 'bold',
          fontSize: '20'
        }
      }
    },
    handleCustomMenu () {
      if (this.selectionList.length !== 1) {
        this.$message.warning('请选择一个公众号')
        return
      }
      this.menuShow = true
      this.mpMenu = { buttons: [] }
      this.appId = this.ids[0]
      this.getWxMenu()
    },
    rowClick (row, event, column) {
      this.$refs.crud.rowView(row, column)
    },
    refresh ({ page, searchForm }) {
      this.onLoad(page)
    },
    beforeOpen (done, type) {
      // if (['edit', 'view'].includes(type)) {
      // const idParams = { id: this.form.id }
      // this.$store.dispatch(getWxMpByIdAction, idParams).then((res) => {
      //   const resCode = res.code
      //   const errorMsg = res.message
      //   if (resCode === 0) {
      //     this.form = res.data
      //   } else {
      //     this.$message({
      //       type: 'error',
      //       message: errorMsg || `查询数据失败,请稍后再试!`
      //     })
      //   }
      // }).catch((err) => {
      //   console.log(err)
      //   this.$message({
      //     type: 'error',
      //     message: `查询数据异常,请稍后再试!`
      //   })
      // })
      // }
      done()
    },
    searchReset () {
      this.query = {}
      this.onLoad(this.page)
    },
    searchChange (params, done) {
      done()
      this.query = params
      this.page.currentPage = 1
      this.onLoad(this.page, params)
    },
    selectionChange (list) {
      this.selectionList = list
    },
    selectionClear () {
      this.selectionList = []
      this.$refs.crud.toggleSelection()
    },
    currentChange (currentPage) {
      this.page.currentPage = currentPage
    },
    sizeChange (pageSize) {
      this.page.pageSize = pageSize
    },
    onLoad (page, params = {}) {
      this.loading = true
      let queryData = {
        pageNo: page.currentPage,
        pageSize: page.pageSize
      }
      queryData = Object.assign(queryData, Object.assign(params, this.query))
      this.$store.dispatch(getWxMpPageListAction, queryData).then((res) => {
        this.loading = false
        const resCode = res.code
        const errorMsg = res.message
        if (resCode === 0) {
          const data = res.data
          this.page.total = parseInt(data.total)
          this.data = data.records
          this.selectionClear()
        } else {
          this.$message({
            type: 'error',
            showClose: true,
            message: errorMsg || '查询数据失败,请稍后再试!'
          })
        }
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'error',
          showClose: true,
          message: '查询数据异常,请稍后再试!'
        })
      })
    }
  },
  head () {
    return {
      title: '微信管理 | ' + this.website.name,
      meta: [
        { hid: 'description', name: 'description', content: '微信管理' }
      ]
    }
  }
}
</script>
<style src="@/assets/css/wx-menu.css"></style>
<style scoped>
  @import '@/assets/css/wx-menu.css';
  .tip {
    padding: 8px 16px;
    background-color: #ecf8ff;
    border-radius: 4px;
    border-left: 5px solid #50bfff;
    margin: 20px 0;
  }
  .tip p {
    font-size: 14px;
    color: #5e6d82;
    line-height: 1.5em;
  }
</style>
